<script setup>
import { ref } from 'vue'
import socket from '../utils/socket';
import { userIdStore } from '../utils/id';
import { useUserStore } from '../stores/user'  // 添加这行


const idStore = userIdStore();
const userStore = useUserStore();
const Data = ref({
  type: "message",
  payload: {
    "content": "Hello",
    "sender": "user123"
  },
  timestamp: new Date().toISOString() // 确保时间戳有实际值
});
// const LoginData = ref({
//   type: "LOGIN",
//   payload: {
//     "username": "molidis",
//     "password": "123456"
//   },
//   timestamp: new Date().toISOString() // 确保时间戳有实际值
// });
const RegisterData = ref({
  type: "REGISTER",
  payload: {
    "username": "ljw",
    "password": "123456"
  },
  timestamp: new Date().toISOString() // 确保时间戳有实际值
});

const SINGLE_MESSAGE_Data = ref({
  type: "SINGLE_MESSAGE",
  payload: {
    "senderId": "molidis",
    "targetId": "Li",
    "content": "你好"
  },
  timestamp: new Date().toISOString() // 确保时间戳有实际值
});

const link = () => {
  //socket获取连接
  // socket = new WebSocket('ws://localhost:9000/ws');
}

const sendMsg = () => {
  // 将Data.value转换为JSON字符串后发送
  const jsonData = JSON.stringify(Data.value);
  socket.send(jsonData);
}
// const sendLoginMsg = () => {
//   socket.send(JSON.stringify(LoginData.value));
// }
const sendRegisterMsg = () => {
  socket.send(JSON.stringify(RegisterData.value));
}
const sendSINGLEMsg = () => {
  socket.send(JSON.stringify(SINGLE_MESSAGE_Data.value));
}
const sendSingleMsg1 = () => {
  //给molidis
  SINGLE_MESSAGE_Data.value.payload.senderId = 2;
  SINGLE_MESSAGE_Data.value.payload.targetId = 1;
  SINGLE_MESSAGE_Data.value.payload.content = "你好molidis";
  socket.send(JSON.stringify(SINGLE_MESSAGE_Data.value));
}
const sendSingleMsg2 = () => {
    //给ljw
  SINGLE_MESSAGE_Data.value.payload.senderId = 1;
  SINGLE_MESSAGE_Data.value.payload.targetId = 2;
  SINGLE_MESSAGE_Data.value.payload.content = "你好ljw";
  socket.send(JSON.stringify(SINGLE_MESSAGE_Data.value));
}



const JoinRoomData = ref({
  type: "JOIN_ROOM",
  payload: {
    "senderId": "molidis",
    "targetId": "Li",
    "content": "你好"
  },
  timestamp: new Date().toISOString() // 确保时间戳有实际值
});
const sendJoinRoomMsg = () => {
    //给ljw
  socket.send(JSON.stringify(JoinRoomData.value));
}

const RoomMsgData = ref({
  type: "ROOM_MESSAGE",
  payload: {
    "senderId": "molidis",
    "targetId": "Li",
    "content": "你好"
  },
  timestamp: new Date().toISOString() // 确保时间戳有实际值
});
const sendRoomMsg = () => {
  socket.send(JSON.stringify(RoomMsgData.value));
}


// 新增登录表单数据
const loginForm = ref({
  username: '',
  password: ''
})
// 新增响应数据存储
const loginResponse = ref(null)




import { useRouter } from 'vue-router';
const router = useRouter()

// 修改后的登录方法
const sendLoginMsg = () => {
  // 先打印登录信息，确认数据是否正确
  console.log("正在尝试登录，用户信息：", {
    username: loginForm.value.username,
    password: loginForm.value.password
  });

  const data = {
    type: "LOGIN",
    payload: {
      username: loginForm.value.username,
      password: loginForm.value.password
    },
    timestamp: new Date().toISOString()
  }
  console.log("click");
  console.log(loginForm.value);
  socket.send(JSON.stringify(data));
}
socket.addEventListener('message', (event) => {
    const response = JSON.parse(event.data);
    if (response.responseMsg === "登录成功") {
      loginResponse.value = response;
      idStore.setId(response.data);
      userStore.login(loginForm.value.username, loginForm.value.password);
      console.log("正在尝试将用户信息保存到userStore，用户信息：", {
      username: loginForm.value.username,
      password: loginForm.value.password
    });
      // 登录成功后，跳转到聊天页面
      console.log("登录：", response);
      router.push('/chat');
    } else if (response.responseMsg === "ONLINE_USERS") {
      onlineUsers.value = response.data;
      console.log("当前在线用户有：", onlineUsers.value);
    } else if (response.responseMsg === "NOTIFICATION") {
      // ✅ 实时通知处理
      alert("【通知】" + response.data);
      console.log("收到通知：", response.data);
    } else if (response.responseMsg === "SINGLE_MESSAGE") {
      alert(`📩 新消息：${response.data}`);
      console.log("收到私聊消息：", response.data);
    } else if (response.responseMsg === "ROOM_MESSAGE") {
      // alert(`👥 群聊消息：${response.data}`);
      console.log("收到群聊消息：", response.data);
    } else if (response.responseMsg === "HEARTBEAT_ACK") {
      console.log("收到心跳确认：", response.data);
    } else if (response.responseMsg === "HISTORIES_MESSAGE") {
      onlineUsers.value = response.data;
      console.log("当前在线用户：", onlineUsers.value);
    } else 
    {
      console.log("收到其他类型消息：", response);
    }

  });
const onlineUsers = ref([]);  // 新增在线用户数据




</script>
<template>
  <div>
    <button width="500px" @click="link()">重新连接</button>
  </div>
  <div>
    <button width="500px" @click="sendMsg()">测试</button>
  </div>
  <div>
    <button width="500px" @click="sendLoginMsg()">登录</button>
  </div>
  <div>
    <button width="500px" @click="sendRegisterMsg()">注册</button>
  </div>
  <div>
    <button width="500px" @click="sendSINGLEMsg()">私发信息</button>
  </div>
  <div>
    <button width="500px" @click="sendSingleMsg1()">发信息给molidis</button>
  </div>
  <div>
    <button width="500px" @click="sendSingleMsg2()">发信息给ljw</button>
  </div>
  <div>
    <button width="500px" @click="sendJoinRoomMsg()">加入群聊</button>
  </div>
  <div>
    <button width="500px" @click="sendRoomMsg()">群发消息"发大家好"</button>
  </div>


  <div>
    <!-- 新增输入框 -->
    <input v-model="loginForm.username" placeholder="用户名">
    <input v-model="loginForm.password" type="password" placeholder="密码">
    <button @click="sendLoginMsg">登录</button>
    <!-- 显示返回结果 -->
    <div v-if="loginResponse">
      登录结果：{{ loginResponse }}
    </div>
  </div>

  <div>
  <h3>当前在线用户列表：</h3>
  <ul>
    <li v-for="user in onlineUsers" :key="user.id">{{ user.username }}</li>
  </ul>
</div>

</template>
